﻿

using System;
using AutoMapper;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

using Oliving.Edge.AuthHelper;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IServices;
using Oliving.Edge.Model.Dto;
using Oliving.Edge.IServices.WY;
using Oliving.Edge.Model.Dto.WY;
using Oliving.Edge.Model.Models.XLT;
using System.Linq.Expressions;
using Oliving.Edge.Common.Extensions;
using Oliving.Edge.Model.DtoUI;

namespace Oliving.Edge.Controllers
{
    [ApiController]
    [Route("api/WY_Company")]
    [Authorize(Permissions.Name)]
    public class WY_CompanyController : OlivingControll
    {
        IMapper _mapper;
        private readonly IWY_CompanyServices _WY_CompanyServices;
        private readonly ILogger<WY_CompanyController> _logger;
        private readonly IWY_ProjectServices _WY_ProjectServices;


        public WY_CompanyController(
                IHttpContextAccessor accessor, PermissionRequirement requirement,
                IMapper mapper, ILogger<WY_CompanyController> logger,
                IWY_CompanyServices WY_CompanyServices,
                IWY_ProjectServices WY_ProjectServices
            ) : base(accessor, requirement)
        {
            _logger = logger;
            _mapper = mapper;
            _WY_CompanyServices = WY_CompanyServices;
            _WY_ProjectServices = WY_ProjectServices;
        }


        #region Base

        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/Get")]
        public async Task<MessageModel<WY_CompanyDto>> Get(string id)
        {
            var data = new MessageModel<WY_CompanyDto>();
            WY_Company model = await _WY_CompanyServices.QueryById(id);
            if (model == null)
            {
                data.response = null;
                data.msg = "数据不存在！";
                data.success = false;
            }
            else
            {
                var dto = _mapper.Map<WY_CompanyDto>(model);
                data.response = dto;
                data.msg = "获取成功！";
                data.success = true;
            }
            return data;
        }




        [HttpGet]
        [Route("/api/[controller]/GetList")]
        [AllowAnonymous]
        public async Task<MessageModel<List<WY_CompanyDto>>> GetList(string key = "")
        {
            var data = new MessageModel<List<WY_CompanyDto>>();
            Expression<Func<WY_Company, bool>> whereExpression = _WY_Company => true;
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            else
            {
                //   whereExpression = whereExpression.And(d =>
                //           d.Canning_Car.Contains(key) 
                //       );
            }

            whereExpression = whereExpression.And(d => d.DeleteMark != 1);
            var dbData = await _WY_CompanyServices.Query(whereExpression);

            //var data = await _WY_CompanyServices.QueryPageList(whereExpression, page, PageSize, sidx, order);

            List<WY_CompanyDto> list = _mapper.Map<List<WY_CompanyDto>>(dbData);

            List<WY_CompanyDto> listChild = list.ConvertTreeList("", "Id", "CompanyPid", "children");
            data.response = listChild;
            data.msg = "获取成功！";
            data.success = true;

            return data;
        }





        [HttpGet]
        [Route("/api/[controller]/GetPageList")]
        public async Task<MessageModel<PageModel<WY_CompanyPageDto>>> GetPageList(int page = 1, int PageSize = 20, string sidx = "", string order = "", string key = "")
        {
            Expression<Func<WY_Company, bool>> whereExpression = _WY_Company => true;
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            else
            {
                //   whereExpression = whereExpression.And(d =>
                //           d.Canning_Car.Contains(key) 
                //       );
            }

            var data = await _WY_CompanyServices.QueryPageList(whereExpression, page, PageSize, sidx, order);

            return new MessageModel<PageModel<WY_CompanyPageDto>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }



        [HttpPut]
        [Route("/api/[controller]/Update")]
        public async Task<MessageModel<string>> Update([FromBody] WY_CompanyDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && !string.IsNullOrEmpty(dto.Id))
            {
                WY_Company model = await _WY_CompanyServices.QueryById(dto.Id);
                if (model != null)
                {
                    model.CompanyName = dto.CompanyName;
                    model.CompanyPid = dto.CompanyPid;
                    model.Address = dto.Address;
                    model.Telephone = dto.Telephone;
                    model.CompanyProfile = dto.CompanyProfile;
                    model.CompanyWebsite = dto.CompanyWebsite;
                    model.Lat = dto.Lat;
                    model.Lng = dto.Lng;
                    model.SortCode = dto.SortCode;

                    model.EnabledMark = dto.EnabledMark;


                    model.Modify(_accessor, model.Id);
                    data.success = await _WY_CompanyServices.Update(model);

                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = dto.Id.ObjToString();
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "参数异常，您要更新的数据不存在";
                }
            }
            else
            {
                data.success = false;
                data.msg = "参数异常";
            }
            return data;
        }





        [HttpPost]
        [Route("/api/[controller]/Add")]
        public async Task<MessageModel<string>> Add(WY_Company dto)
        {
            var data = new MessageModel<string>();
            dto.Create(_accessor);
            int id = await _WY_CompanyServices.AddGuid(dto);

            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }
            return data;
        }




        [HttpDelete]
        [Route("/api/[controller]/Delete")]
        public async Task<MessageModel<string>> Delete(string id)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(id))
            {
                var userDetail = await _WY_CompanyServices.QueryById(id);
                userDetail.DeleteMark = 1;
                data.success = await _WY_CompanyServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.Id.ObjToString();
                }
            }
            return data;
        }





        [HttpDelete]
        [Route("/api/[controller]/BatchDelete")]
        public async Task<MessageModel<string>> BatchDelete(string ids)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                if (false)
                {
                    #region 软删除

                    int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s));

                    WY_Company model = new WY_Company();
                    //  model.C_State = -1;          ???????????????????
                    string whereStr = " Id in (" + ids + ")";
                    List<string> colList = new List<string>();
                    //  colList.Add("C_State");    ???????????????????
                    List<string> colHL = new List<string>();

                    bool isOK = await _WY_CompanyServices.Update(model, colList, colHL, whereStr);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }
                {
                    #region 直接删除 

                    object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                    bool isOK = await _WY_CompanyServices.DeleteByIds(list);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }
                    #endregion
                }
            }
            return data;
        }


        #endregion




        /// <summary>
        ///  树形结构，为页面的下拉tree 提供数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/api/[controller]/GetListToUI")]
        [AllowAnonymous]
        public async Task<MessageModel<List<CascaderOptionsDto>>> GetListToUI()
        {
            var data = new MessageModel<List<CascaderOptionsDto>>();
            Expression<Func<WY_Company, bool>> whereExpression = _WY_Company => true;

            List<WY_Company> dbData = await _WY_CompanyServices.Query(whereExpression);

            List<CascaderOptionsDto> outList = new List<CascaderOptionsDto>();
            foreach (WY_Company ui in dbData)
            {
                outList.Add(new CascaderOptionsDto
                {
                    value = ui.Id,
                    label = ui.CompanyName,
                    ParentCode = ui.CompanyPid,
                });
            }

            List<CascaderOptionsDto> listChild = outList.ConvertTreeList("", "value", "ParentCode", "children");
            data.response = listChild;
            data.msg = "获取成功！";
            data.success = true;

            return data;
        }



        /// <summary>
        ///  树形结构(公司和项目)，为部门页面提供左侧选择数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/api/[controller]/GetTreeComPro")]
        [AllowAnonymous]
        public async Task<MessageModel<List<TreeDto_ComPro>>> GetTreeComPro()
        {
            var data = new MessageModel<List<TreeDto_ComPro>>();
            Expression<Func<WY_Company, bool>> whereExpression = _WY_Company => true;

            whereExpression = whereExpression.And(d => d.DeleteMark == 0);
            List<WY_Company> dbData = await _WY_CompanyServices.Query(whereExpression);

            List<TreeDto_ComPro> outList = new List<TreeDto_ComPro>();
            foreach (WY_Company ui in dbData)
            {
                outList.Add(new TreeDto_ComPro
                {
                    value = ui.Id,
                    label = ui.CompanyName,
                    ParentCode = ui.CompanyPid,
                    CompanyID = ui.Id,
                    ProjectID = ""
                });
            }
            Expression<Func<WY_Project, bool>> whereExpression_WY_Project = _WY_Project => true;

            whereExpression_WY_Project = whereExpression_WY_Project.And(d => d.DeleteMark == 0);

            List<WY_Project> dbDataWY_Project = await _WY_ProjectServices.Query(whereExpression_WY_Project);

            foreach (WY_Project ui in dbDataWY_Project)
            {
                outList.Add(new TreeDto_ComPro
                {
                    value = ui.Id,
                    label = ui.ProName,
                    ParentCode = ui.ComID,
                    CompanyID = ui.ComID,
                    ProjectID = ui.Id
                });
            }


            List<TreeDto_ComPro> listChild = outList.ConvertTreeList("", "value", "ParentCode", "children");
            data.response = listChild;
            data.msg = "获取成功！";
            data.success = true;

            return data;
        }






    }
}

